/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-01-08 14:22:52
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-06-28 22:00:20
 * @FilePath: \Scene_Back\src\auth\local.strategy.ts
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-02-22 16:27:52
 * @FilePath: \Scene_Back\src\auth\local.strategy.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { compareSync } from 'bcryptjs';
import { PassportStrategy } from '@nestjs/passport';
import { IStrategyOptions, Strategy } from 'passport-local';
import { User } from 'src/user/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BadRequestException, HttpException, HttpStatus, Injectable } from '@nestjs/common';

@Injectable()
export class LocalStorage extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {
    super({
      usernameField: 'email',
      passwordField: 'password',
    } as IStrategyOptions);
  }

  async validate(email: string, password: string) {
    const user = await this.userRepository
      .createQueryBuilder('user')
      .addSelect('user.password')
      .where('user.email=:email', { email })
      .getOne();
    if (!user) {
      throw new BadRequestException('邮箱验证不正确！');
    }

    if (!compareSync(password, user.password)) {
      throw new BadRequestException('密码错误！');
    }
    return user;
  }
}
